# coding: utf-8

#
#部署：塞班s60v3手机、PythonForS60 2.0.0(pips、shell)、建议使用无线网、放入手机c:\data\python
#


#
#网络接入点处理
#步骤：选择接入点 > 将所选接入点存入文件 > 设置所选为默认接入点
#      有需要联网的代码,则在其前读取默认接入点,无需每次连接都要设置接入点 
#
import sys
import appuifw
try:
    # http://discussion.forum.nokia.com/forum/showthread.php?p=575213
    # Try to import 'btsocket' as 'socket' (just for 1.9.x and up)
    #对于版本>=PythonForS60_1.9.x的pys60需要这样用,只是import btsocket是不行的
    sys.modules['socket'] = __import__('btsocket')
except ImportError:
    pass
import socket

#自定义接入点并保存
def set_accesspoint():
    apid = socket.select_access_point()     #弹出手机的接入点选择菜单
    f = open('c:\\data\\python\\apid.txt','w')  #打开文件
    f.write(repr(apid))     #将所选的接入点id号写进文件
    f.close()
    appuifw.note(u"Saved default access point ", "info")    #手机信息提醒框
    apo = socket.access_point(apid)     #通过接入点id号获取接入点完整信息
    socket.set_default_access_point(apo)    #设置默认接入点
#清除自定义接入点
def unset_accesspoint():
    f = open('c:\\data\\python\\apid.txt','w')
    f.write(repr(None))     #设接入点id号为None
    f.close()
    appuifw.note(u"Default access point is unset ", "info")
#读取设置的接入点
def read_accesspoint():
    try:
        f=open('c:\\data\\python\\apid.txt','rb')
        setting = f.read()  #读取接入点文件
        apid = eval(setting)    #执行
        f.close()
        if not apid == None :   #是否为None,即检测是否设置了自定义接入点
            apo = socket.access_point(apid)
            socket.set_default_access_point(apo)
        else:
            set_accesspoint()
    except:
        set_accesspoint()


#
#邮件发送处理
#这段代码来源：http://www.oschina.net/code/snippet_944211_27429
#因PyS602.0是已python2.5.4为核心,py2.6才加入with,故代码中对with语句做了修改
#注意：这里使用的是QQ邮箱给自己发邮件,
#       QQ的SMTP查看：http://service.mail.qq.com/cgi-bin/help?subtype=1&no=167&id=28
#       开通QQ的pop3功能：http://service.mail.qq.com/cgi-bin/help?subtype=1&no=166&id=28
#
import os.path
import smtplib
from email import encoders
from email.utils import formatdate
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
import mimetypes

class Email:
    """SMTP and sender define
    """
    def __init__(self, **kwg):
        """init setting include smpt server/port 
            and sender "from" address
        """
        self._setting = dict(kwg)

    def send(self, msg):
        """send msg by setting's smtp server
        """
        smtp = smtplib.SMTP()
        sender = self._setting.get("From")
        pwd = self._setting.get("Pwd")
        read_accesspoint()  #******自动选择接入点,这里不能少,不然每发一封邮件都会提示你用哪个接入点联网******
        smtp.connect(
            self._setting.get('server'),
            self._setting.get('port', 25)   #大部分邮箱都是默认25端口
            )
        if pwd:
            smtp.login(sender, pwd)
        msg["From"] = msg.get("From", sender) 
        smtp.sendmail(
            msg['From'],
            msg['To'].split(',')+
            msg['Cc'].split(','),
            msg.as_string()
            )
        smtp.quit()

def _attach_text(file_name, subtype):
    """inner function to attach text file
    """
    handle = open(file_name)
    try:
        mmt = MIMEText(handle.read(), _subtype=subtype)
    finally:
        handle.close()
    return mmt

def _attach_image(file_name, subtype):
    """inner function to attach image file
    """
    handle = open(file_name, 'rb')
    return MIMEImage(handle.read(), _subtype=subtype)

def _attach(file_name, maintype, subtype):
    """inner function to attach file
    """
    handle = open(file_name, 'rb')
    file_msg = MIMEBase(maintype, subtype)
    file_msg.set_payload(handle.read())
    encoders.encode_base64(file_msg)
    return file_msg

attach_switcher = {
    'text': _attach_text,
    'image': _attach_image,
    }

def attach(msg, file_name):
    """attach a file to the message package:msg
    """
    ctype, encoding = mimetypes.guess_type(file_name)
    if ctype is None or encoding is not None:
        # No guess could be made, or the file is encoded (compressed), so
        # use a generic bag-of-bits type.
        ctype = 'application/octet-stream'
    maintype, subtype = ctype.split('/', 1)
    attach_proc = attach_switcher.get(maintype)
    if not attach_proc:
        file_msg = _attach(file_name, maintype, subtype)
    else:
        file_msg = attach_proc(file_name, subtype)
    # Set the filename parameter
    file_msg.add_header('Content-Disposition', 'attachment', 
        filename=os.path.split(file_name)[-1])
    msg.attach(file_msg)
    return msg

def writemail(coding='utf-8', **kwg):
    """write a email message
    """
    msg = MIMEMultipart()
    msg["To"] = kwg.get('To', 'exampleTo@mail.com')   #发送,默认设为exampleTo@mail.com,调用writemail()时也可给出
    msg["Cc"] = kwg.get('Cc', 'exampleTo@mail.com')   #抄送,默认设为exampleCc@mail.com,调用writemail()时也可给出
    msg['Date'] = formatdate()
    msg["Subject"] = Header(kwg.get('Subject', 'No Subject'), coding)
    if "Html" in kwg:
        msg.attach(MIMEText(
            kwg.get('Html').encode(coding), 
            'html', 
            _charset=coding
            ))
    if "Context" in kwg:
        msg.attach(MIMEText(
            kwg.get('Context').encode(coding), 
            'plain', 
            _charset=coding
            ))
    
    attaches = kwg.get('attach')
    if not attaches:
        return msg
    if isinstance(attaches, (str, unicode)):    #如果附件名称是str,对其做list处理
        attaches = [attaches]
    if isinstance(attaches, (list, tuple)):
        return reduce(attach, [filename for filename in attaches 
                if os.path.isfile(filename)], 
            msg)
    else:
        return msg

def send():
    email = Email(
        server="smtp.qq.com",           #修改 发送人邮箱SMTP
        From='xxx@qq.com',        #修改 发送人邮箱地址
        Pwd='xxx',              #修改 发送人邮箱密码
        )
    email.send(writemail(
            To="xxx@qq.com",      #修改 接收人邮箱地址
            Cc="xxx@qq.com",      #修改 抄送人邮箱地址
            Subject=u"手机监控",    #主题
            Context=u"""此邮件将被接收程序读取,并自动删除.""",
            attach=[
               u'c:\\data\\python\\monitor.jpg',
               ],   #附件列表
            ))


#
#手机拍照处理
#
import camera, e32, time
count = 0
imgfile = u"c:\\data\\python\\monitor.jpg"      #此处的照片名称和监控端判断附件文件名对映
set_accesspoint()   #设置默认网络接入点
while True:
   try:
      print "Being camera..."
      im=camera.take_photo()    #拍照
      photo.text((0,20),unicode(time.strftime("%Y/%m/%d    %H:%M:%S")),fill=0xffff00)   #给图片左上角加入黄色字体的拍摄日期文字
      im.save(imgfile)          #保存照片
      count=count+1             #拍摄次数
      print str(count)+" image finish."
      print "Sending e-mail..."     #到此执行基本在3s左右
      send()    #发送照片邮件大概3-7秒左右的执行时间
      print "Sent successfully.\n"
      #e32.ao_sleep(3)      #不间断
   except Exception, e:
      print str(count)+" Failed to send! Error message:\n"+str(e)
      unset_accesspoint()   #程序退出后【最好】要清掉自定义接入点,这段也可不执行
      sys.exit(1)       #抛出异常跳出